//
//  LocalNotificationManager.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/17.
//

import Foundation
import SwiftUI
import UserNotifications
import Foundation
import UserNotifications

//本地推送
class LocalNotificationManager {
    static let shared = LocalNotificationManager()
    private init() {}
    
    // 请求通知权限
    func requestAuthorization(completion: @escaping (Bool) -> Void = { _ in }) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                showLog("通知权限已授权")
                completion(true)
            } else if let error = error {
                showLog("授权失败: \(error.localizedDescription)")
                completion(false)
            }
        }
    }
    
    // 调度通知（带日期参数）
    func scheduleNotification(
        title: String,
        subtitle: String,
        date: Date = Date().addingTimeInterval(5),
        identifier: String = UUID().uuidString
    ) {
        // 检查权限
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            guard settings.authorizationStatus == .authorized else {
                showLog("未获得通知权限")
                return
            }
            
            // 创建通知内容
            let content = UNMutableNotificationContent()
            content.title = title
            content.subtitle = subtitle
//            content.body = "点击查看详细信息"
            content.sound = .default
            
            // 转换日期为触发条件
            let calendar = Calendar.current
            let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
            let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
            
            // 创建请求
            let request = UNNotificationRequest(
                identifier: identifier,
                content: content,
                trigger: trigger
            )
            
            // 添加通知
            UNUserNotificationCenter.current().add(request) { error in
                if let error = error {
                    showLog("调度通知失败: \(error.localizedDescription)")
                } else {
                    showLog("通知已调度: \(identifier)")
                }
            }
        }
    }
    
    // 取消所有待处理通知
    func cancelAllNotifications() {
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        showLog("已取消所有待处理通知")
    }
}


// 扩展处理前台通知展示
extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                               willPresent notification: UNNotification,
                               withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        showLog("💡 即将展示前台通知: \(notification.request.identifier)")
        // 允许在前台显示通知横幅和播放声音
        completionHandler([.banner, .sound, .badge])
        NotificationCenter.default.post(name: .push, object: true)
    }
}
